package com.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.exam.entity.Admin;
import com.exam.entity.AdminLoginParam;
import com.exam.mapper.AdminMapper;
import com.exam.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exam.util.JwtTokenUtil;
import com.exam.util.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.PasswordAuthentication;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员信息表 服务实现类
 * </p>
 *
 * @author zyh
 * @since 2023-03-09
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Autowired(required = false)
    private AdminMapper adminMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean login(String adminId,String pwd,String code,HttpServletRequest request) {
//        String captcha = (String) request.getSession().getAttribute("captcha");
        ValueOperations opr = redisTemplate.opsForValue();
        String captcha =(String) opr.get("code");
        if (captcha==null || captcha.equals(" ")){
            return RespBean.error("验证码过期，请点击图片刷新！");
        }
        if (StringUtils.isBlank(code) || !captcha.equals(code)) {
            return RespBean.error("验证码填写错误！");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(adminId);
        if (null == userDetails || !passwordEncoder.matches(pwd, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确!");
        }
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userDetails, null,
                        userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String token = jwtTokenUtil.generateToken(userDetails);
        log.info("token:{}",token);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        log.info("登录状态：登录成功");
        return RespBean.success("登录成功", tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String adminId) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("adminId",adminId));
    }

    @Override
    public RespBean upadteAdminPwd(String pwd, String xpwd, String adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(pwd, admin.getPassword())) {
            admin.setPwd(encoder.encode(xpwd));
            int result = adminMapper.updateById(admin);
            if (1 == result) {
                return RespBean.success("更新成功!");
            }
        }
        return RespBean.error("更新失败!");
    }
}
